package com.mydomain.debtbook;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public abstract class ListTableActivity extends ListActivity {
	protected DebtAdapter myDBAdapter;
	protected Cursor cursor;
	protected SimpleCursorAdapter cursorAdapter;
	protected int layoutId;
	protected String myTable;
	protected int[] TO_ITEM;

	protected abstract void intialize();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		intialize();
		setContentView(R.layout.dblistmain);
		myDBAdapter = ((debtBookApplication) this.getApplication())
				.getDatabaseAdapter();
		cursor = getListCursor(myTable);
		showListItems(cursor, myTable);
		ListView lv = getListView();
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				goCalledActivity(cursor.getString(cursor
						.getColumnIndex(DebtAdapter._ITEM)));

			}
		});

	}

	private Cursor getListCursor(String tableName) {

		Cursor myCursor = myDBAdapter.getAllItemCursor(tableName);
		if (myCursor != null) {
			startManagingCursor(myCursor);
		}
		return myCursor;

	}

	private void showListItems(Cursor cursor, String tableName) {
		cursorAdapter = new SimpleCursorAdapter(this, layoutId, cursor,
				myDBAdapter.getFromList(tableName), TO_ITEM);
		setListAdapter(cursorAdapter);
	}

	private void goCalledActivity(String item) {

		Intent returnIntent = new Intent();
		returnIntent.putExtra("ItemId", item);
		setResult(RESULT_OK, returnIntent);
		finish();
	}

}
